package com.corticon.dialogs.util;

import com.corticon.dialogs.dao.GenericDAO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 *
 * @author Yanglifan
 */
@Component
public class BeanSupport implements ApplicationContextAware {

    private ApplicationContext applicationContext;
    private String DAO_SUFFIX = "DAO";

    public Object findBeanByName(String beanName) {
        Object bean = null;

        bean = applicationContext.getBean(beanName);

        return bean;
    }

    /**
     * This method load DAO according to the type of the entity.
     *
     * @param <T>
     * @param entity
     * @return
     */
    public <T> GenericDAO loadDAO(Class<T> entity) {
        String entityName = StringUtils.uncapitalize(entity.getSimpleName());
        String daoName = entityName + DAO_SUFFIX;
        return (GenericDAO) findBeanByName(daoName);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
